package com.yc.thread.basic;

/**
 * 精灵线程  其他线程运行结束  精灵线程也会结束
 *
 * @author zwei
 * @create 2024-07-15 18:59
 */
public class Test10_daemon {
    public static void main(String[] args) {
        Thread t1=new CommonThread();
        //新建任务  在绑定到一个线程上
        Thread t2=new Thread(new MyDaemon());
        //设置为守护线程
        t2.setDaemon(true);
        //正确做法  线程运行前设置守护线程
        t2.start();
        t1.start();
        System.out.println("主线程已经运行完了");
    }
}
//线程
class CommonThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("用户线程" + i + "次执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

class MyDaemon implements Runnable {

    @Override
    public void run() {
        for (long i = 0; i < 20; i++) {
            System.out.println("守护线程第"+i+"次执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
